package com.chat.websocket;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.chat.websocket.online.OnlineManage;

/**
 * websocket连接时握手，发送信息时不经过这里
 * 
 * @author lwh
 *
 */
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
	private static final Logger logger = Logger.getLogger(WebSocketHandshakeInterceptor.class);
	/**
	 * 裁剪URI, 假设URI合法，进行处理，非法因素留给拦截处理
	 * 
	 * @param URI
	 * @return
	 */
	public Map<String, String> splitParamter(String URI) {
		Map<String, String> map = new HashMap<String, String>(0);
		String[] strs = URI.split("/");
		if (strs.length > 3) {
			map.put("userName", strs[strs.length - 2]);
			map.put("token", strs[strs.length - 1]);
		}
		return map;
	}

	/**
	 * 找不到好的拦截判断(是否符合连接条件)的方法，暂时以裁剪URI解决
	 */
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		logger.info("websocket握手前连接拦截");
		Map<String, String> params = this.splitParamter(request.getURI().toString());
		String userName = params.get("userName");
		String token = params.get("token");
		if (userName != null && token != null) {
			// “预备连接集”存在当前用户，允许连接，反之拒接连接
			boolean flag = OnlineManage.isExistInPlanConnTemp(userName, token);
			if (flag == true) {
				//判断是否已登陆，有则移除
				if ( OnlineManage.isOnlined(userName) ) {
					OnlineManage.removeOnlineUser(userName);
				}
				return true;
			}
		}
		return false;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {
		logger.info("websocket握手后连接拦截");
		Map<String, String> params = this.splitParamter(request.getURI().toString());
		String userName = params.get("userName");
		String token = params.get("token");
		// 用户通过websocket握手后，清除“预备连接集”信息
		if (OnlineManage.isExistInPlanConnTemp(userName, token)) {
			OnlineManage.removeInPlanConnTemp(userName, token);
		}
	}

}
